<template>
  <div id="TeacherManage">
    <a-form layout="inline" style="margin-bottom: 8px">
      <a-form-item label="关键字" class="searchItem">
        <a-input placeholder="请输入" v-model="keyword" />
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="getData"> 查询 </a-button>
      </a-form-item>
      <a-form-item label="">
        <a-button type="primary" @click="addbtn">新增</a-button>
        <a-upload
          class="upload"
          name="file"
          :multiple="true"
          :show-upload-list="false"
          :custom-request="customUploadRequest"
          accept=".xls,.xlsx"
        >
          <a-button type="primary" style="margin-left: 8px">导入</a-button>
        </a-upload>
        <a-button type="primary" style="margin-left: 10px" @click="downClick">导出</a-button>
      </a-form-item>
    </a-form>

    <a-table
      :scroll="{ y: 500 }"
      bordered
      :columns="columns"
      style="margin-top: 30px"
      :data-source="tableData"
      :pagination="tablePagination"
      :rowKey="(record, index) => record.id"
      @change="handleTableChange"
    >
      <template slot="name" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.name">
          <template slot="title">
            <span>{{ record.name }}</span>
          </template>
          <span style="cursor: default">{{ record.name }}</span>
        </a-tooltip>
        <span v-else-if="!record.name">—</span>
      </template>
      <template slot="tapdProjectId" slot-scope="text, record">
        <a-tooltip placement="top" v-if="record.tapdProjectId">
          <template slot="title">
            <p>{{ record.tapdProjectId }}</p>
          </template>
          <span style="cursor: default">{{ record.tapdProjectId }}</span>
        </a-tooltip>
        <span v-else-if="!record.tapdProjectId">—</span>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a-button
          v-if="record.operation"
          type="primary"
          @click="editClick(record)"
          >修改信息</a-button
        >
        <a-button
          v-if="record.operation"
          type="danger"
          style="margin-left: 10px"
          @click="deleteClick(record)"
          >删除</a-button
        >
      </template>
    </a-table>
    <a-modal v-model="visible" :maskClosable="false" :title="title">
      <a-form-model
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
        ref="formRef"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item label="姓名" prop="realName">
          <a-input v-model="form.realName" />
        </a-form-model-item>
        <a-form-model-item label="性别" prop="sex">
          <a-select v-model="form.sex">
            <a-select-option
              v-for="item in sexList"
              :key="item.id"
              :value="item.id"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <!-- <a-form-model-item label="所属班级" prop="classGrade">
          <a-input v-model="form.classGrade" />
        </a-form-model-item>
        <a-form-model-item label="所属届" prop="period">
          <a-input v-model="form.period" />
        </a-form-model-item> -->
        <a-form-model-item label="账号" prop="username">
          <a-input v-model="form.username" :disabled="isDisabled" />
        </a-form-model-item>
        <a-form-model-item label="密码" prop="password">
          <a-input v-model="form.password" />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" class="modalCancel" @click="handleCancel"
          >取消</a-button
        >
        <a-button key="submit" @click="primaryClick" type="primary">
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>
  
  <script>
export default {
  props: {
    role: {},
  },
  data() {
    return {
      keyword: "", //关键字
      isDisabled: true,
      sexList: [
        {
          id: 1,
          label: "男",
        },
        {
          id: 2,
          label: "女",
        },
      ],
      roleList: [
        {
          id: 1,
          label: "用户",
        },
        {
          id: 3,
          label: "管理员",
        },
      ],
      form: {
        realName: "", //姓名
        sex: "", //性别
        role: "", //用户权限
        studentClass: "", //所属班级
        year: "", //所属届
        userName: "", //账号
        password: "", //密码
      },
      rules: {
        realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
        classGrade: [
          { required: true, message: "请输入所属班级", trigger: "blur" },
        ],
        period: [{ required: true, message: "请输入所属届", trigger: "blur" }],
        username: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      visible: false,
      title: null,
      columns: [
        //主页table列的配置
        {
          title: "序列号",
          dataIndex: "id",
          scopedSlots: { customRender: "id" },
        },
        {
          title: "姓名",
          dataIndex: "realName",
          customRender: (text, record) => {
            return record.realName ? record.realName : "—";
          },
        },
        {
          title: "性别",
          dataIndex: "sex",
          customRender: (text, record) => {
            if (record.sex == 1) {
              return "男";
            } else if (record.sex == 2) {
              return "女";
            } else {
              return "-";
            }
          },
        },
        // {
        //   title: "所属班级",
        //   dataIndex: "classGrade",
        //   customRender: (text, record) => {
        //     return record.classGrade ? record.classGrade : "—";
        //   },
        // },
        // {
        //   title: "所属届",
        //   dataIndex: "period",
        //   customRender: (text, record) => {
        //     return record.period ? record.period : "—";
        //   },
        // },
        // {
        //   title: "账号",
        //   dataIndex: "userName",
        //   customRender: (text, record) => {
        //     return record.userName ? record.userName : "—";
        //   },
        // },
        // {
        //   title: "密码",
        //   dataIndex: "password",
        //   customRender: (text, record) => {
        //     return record.password ? record.password : "—";
        //   },
        // },
        {
          title: "操作",
          width: 200,
          dataIndex: "operation",
          scopedSlots: { customRender: "operation" },
        },
      ],
      tableData: [
        //主页表格的数据
      ],
      tablePagination: {
        //主页表格的分页器
        total: 0,
        current: 1,
        pageSize: 10,
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true, //是否可以改变 pageSize
      },
    };
  },
  watch: {
    visible: {
      handler(newVal) {
        if (!newVal) {
          this.$refs.formRef.resetFields && this.$refs.formRef.resetFields(); //重置表单校验
          this.form = {
            realName: "", //姓名
            sex: "", //性别
            studentClass: "", //所属班级
            year: "", //所属届
            userName: "", //账号
            password: "", //密码
          };
        }
      },
    },
  },
  created() {
    this.getData();
  },
  methods: {
    downClick() {
      this.$axios
        .get("/educator/export", {
          params: {
            keyword: this.keyword,
          },
          responseType: "blob", // 关键：指定返回数据类型为 blob
        })
        .then((res) => {
          const downloadUrl = window.URL.createObjectURL(res);
          const link = document.createElement("a"); // 创建隐藏的下载链接
          link.href = downloadUrl;
          const filename = "教员信息.xlsx"; //文件名可以从响应头或请求参数中获取
          link.download = filename;
          link.click();
          link.remove();
        });
    },
    customUploadRequest({ file, onSuccess, onError }) {
      const formData = new FormData();
      // 添加文件到 FormData
      formData.append("file", file);
      // 如果需要其他参数，可以在这里添加
      // formData.append('additionalParam', 'value');
      this.$axios.post("/educator/import", formData).then((res) => {
        if (res.code == 200) {
          this.$message.success("上传成功");
          this.getData();
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.tablePagination.current = pagination.current;
      this.tablePagination.pageSize = pagination.pageSize;
      this.getData();
    },
    deleteClick(row) {
      //点击删除
      let data = {
        id: row.id,
      };
      let that = this;
      this.$confirm({
        title: "确认删除?",
        content: "您确定要删除此项吗?",
        onOk() {
          that.$axios.delete("/educator/delete", { data }).then((res) => {
            if (res.code == 200) {
              that.$message.success("删除成功");
              that.getData();
            }
          });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    editClick(row) {
      //编辑
      this.$axios
        .get("/educator/detail", { params: { id: row.id } })
        .then((res) => {
          for (let i in res.data) {
            this.form[i] = res.data[i];
          }
          this.title = "编辑学员信息";
          this.visible = true;
        });
    },
    addbtn() {
      //新增
      this.isDisabled = false;
      this.title = "新增学员信息";
      this.visible = true;
    },
    handleCancel() {
      this.visible = false;
    },
    primaryClick() {
      this.$nextTick(() => {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            let data = this.form;
            if (this.title == "新增学员信息") {
              this.$axios.post("/educator/create", data).then((res) => {
                if (res.code == 200) {
                  this.$message.success("新增成功");
                  this.getData();
                  this.visible = false; // 关闭模态框
                }
              });
            } else if (this.title == "编辑学员信息") {
              this.$axios.put("/educator/update", data).then((res) => {
                if (res.code == 200) {
                  this.$message.success("编辑成功");
                  this.getData();
                  this.visible = false; // 关闭模态框
                }
              });
            }
          } else {
            console.log("校验失败");
          }
        });
      });
    },
    async getData() {
      let { data } = await this.$axios.get("/educator/page/list", {
        params: {
          page: this.tablePagination.current,
          size: this.tablePagination.pageSize,
          keyword: this.keyword,
        },
      });
      this.tableData = data.records;
      this.tablePagination.total = data.total;
    },
  },
};
</script>
  
<style lang="scss">
#TeacherManage {
  padding: 24px 32px;
  margin: 30px 20px 0 20px;
  border-radius: 2px;
  .upload {
    position: relative;
    .ant-upload-list {
      position: absolute;
      .ant-upload-list-item {
        width: 200px;
      }
    }
  }
}
</style>